import Vue from "vue";

export function actions(url) {
    return {
        // action 默认传入context对象
        Lists ({commit}, filter) {
            return Vue.axios.get(url, {
                params: filter
            });
        },
        Store ({commit}, data) {
            return Vue.axios.post(url, data);
        },
        Update ({commit}, data) {
            return Vue.axios.put(`${url}/${data.id}`, data);
        },
        Destroy ({commit}, id) {
            return Vue.axios.delete(`${url}/${id}`);
        },
        DestroyMultiple ({commit}, ids) {
            return Vue.axios.delete(`${url}/0`, {
                params: {
                    ids: ids,
                }
            });
        },
        Show ({commit}, id) {
            return Vue.axios.get(`${url}/${id}`);
        },
        All ({state, commit}, model = '') {
            if (state.request && state.request.all) {
                return false;
            }
            if (state.request) commit('SET_REQUESTING', 'all')
            return new Promise((resolve, reject) => {
                Vue.axios.get(`admin/api/all/${model}`).then(res => {
                    commit('SET_ALL', res.data);
                    return resolve(res);
                }).catch(error => {
                    return reject(error);
                }).finally(() => {
                    if (state.request) commit('SET_REQUESTED', 'all');
                })
            });
        },
        Download({commit}, filter = {}) {
            filter.download = 1;
            return Vue.axios.get(`${url}`, {
                params: filter,
                responseType: 'blob',
            })
        },
    }
}

export function mutations() {
    return {
        SET_ALL (state, data) {
            state.all = data;
        },
        SET_REQUESTING (state, name) {
            state.request[name] = true;
        },
        SET_REQUESTED (state, name) {
            state.request[name] = false;
        }
    }
}
